package com.rp.api.interceptors;

import cn.hutool.core.util.StrUtil;
import com.google.common.base.Verify;
import com.rp.news.common.ResponseStatusEnum;
import com.rp.news.exception.GraceException;
import com.rp.news.util.RedisOperator;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.sql.Struct;

public class BaseInterceptor {

    @Autowired
    public RedisOperator redis;


    public static final String REDIS_USER_TOKEN = "redis_user_token";
    public static final String REDIS_USER_INFO = "redis_user_info";
    public static final String REDIS_ADMIN_TOKEN = "redis_admin_token";



    public boolean verifyUserIdToken(String userId,String userToken,String prifix){

        if(StrUtil.isNotBlank(userId) && StrUtil.isNotBlank(userToken)){
            String s = redis.get(prifix + ":" + userId);
            if(StrUtil.isBlank(s)){
                GraceException.display(ResponseStatusEnum.UN_LOGIN);
                return false;
            }else {
                if(!s.equalsIgnoreCase(userToken)){
                    GraceException.display(ResponseStatusEnum.TICKET_INVALID);
                    return false;
                }
            }
        }else{

            GraceException.display(ResponseStatusEnum.UN_LOGIN);
            return false;
        }
        return true;
    }


    // 从cookie中取值
    public String getCookie(HttpServletRequest request, String key) {
        Cookie[] cookies = request.getCookies();
        if (cookies == null) {
            return null;
        }
        for(Cookie cookie : cookies){
            if(cookie.getName().equals(key)){
                String value = cookie.getValue();
                return value;
            }
        }
        return null;
    }


}
